<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.thymeleaf.org"
      layout:decorator="layouts/simpleLayout">
<head>

</head>
<body>
<div layout:fragment="bodyContent">
    <div class="row">
        <div class="col-md-12">

            <table class="table table-striped table-hover table-bordered">
                <tr th:if="${#lists.isEmpty(categories)}">
                    <td>
                        No item
                    </td>
                </tr>
                <tr th:each="cg : ${categories}" th:id="${'tr_'+cg.id}">
                    <td width="70%">
                        <strong class="text-center">
                            <a th:href="${'/categories?pid=' + cg.id}" title="click show sub categories" th:text="${cg.name}"></a>
                        </strong>
                    </td>
                    <td>
                        <a th:if="${cg.level < 1}" th:href="${'/category/new/'+cg.id}" th:attr="data-id=${cg.id},data-name=${cg.name}" onclick="addSubCategory(this)">add</a>
                        <a href="#" th:attr="onclick='delCategory(\''+ ${cg.id} +'\')'">delete</a>
                    </td>
                </tr>
            </table>
        </div>
    </div>

    <script src="/webjars/jquery/1.11.1/jquery.min.js"></script>
    <script src="/webjars/jquery-ui/1.11.4/jquery-ui.js"></script>
    <script>
        var dialog;
        var addCategoryForm;
        $(document).ready(function(){
        /**
            dialog = $("#add_new_category_dialog").dialog({
                autoOpen:false,
                height: 400,
                width: 350,
                modal: true
            });

            addCategoryForm = dialog.find("form")[0];
            */
        });
        function addSubCategory(parentCategory){
            //dialog.dialog( "open" );
        }

        function delCategory(id){
            if(confirm("Are you sure to delete this category?")){
                $.ajax({
                    url:'/category/delete',
                    type:'post',
                    dataType:'json',
                    data:{'id':id},
                    success:function(data){
                        alert("Delete success.");
                        $("#tr_"+id).remove();
                    },
                    error:function(er){
                        alert("Delete selected category failed.");
                        console.log(JSON.stringify(er));
                    }
                });
            }
        }
    </script>
</div>

</body>
</html>